package org.jaaksi.demo.ptr.adapter;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Fcy on 2016/3/26.<br/>
 */
public abstract class SimpleCallBack<T> implements Callback {

  public static final int SUCCESS = 0;
  public static final int ERROR_NET = -1;
  public static final int ERROR_PARSE = -2;
  public static final int ERROR_SERVER = -3;

  private Class<T> cls;

  public SimpleCallBack(Class<T> cls) {
    if (cls == null) {
      throw new IllegalArgumentException("class can must not be null");
    }
    this.cls = cls;
  }

  /**
   * connection server error
   */
  @Override public void onFailure(Call call, IOException e) {
    onResponse(call, null, ERROR_NET);
  }

  @Override public void onResponse(Call call, Response response) throws IOException {
    if (response.code() >= 200 && response.code() < 300) {
      T t = parseResponse(response);
      onResponse(call, t, t == null ? ERROR_PARSE : SUCCESS);
    } else {
      onResponse(call, null, ERROR_SERVER);
    }
  }

  public abstract void onResponse(Call call, T response, int errorCode);

  public T parseResponse(Response response) {
    try {
      return JSON.parseObject(response.body().string(), cls);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
